import { FC, useEffect, useState, useRef } from 'react'
import { useSelector } from 'dva'
import styled from 'styled-components'
import io from 'socket.io-client';
import axios from 'axios'
import ImageView from '@/components/ImageView/index'

const socket = (io as any)('http://localhost:3000')

// socket.on('sendMsg', (res: any) => {
//   console.log('res:', res)
// })

const Chat:FC<any> = (props) => {
  const [list, setList] = useState<any>([]);
  const inpt:any = useRef();
  const mainDom:any = useRef();
  const { users: { userId, brokerId = 19, submitId} } = useSelector((s:any) => s)

  // 监听到用户发送消息，然后重新请求数据渲染

  useEffect(() => {
    getRecords()
    socket.on('sendMsg', (data:any) => {
      console.log('data:', data)
      // 调用获取用户信息接口
      getRecords()
    })
  }, [])

  useEffect(() => {
    // 监听到接口拿过来数据，就让滚动条滚动到最下面
    scrollToView()
  }, [list])

  // 用户信息
  const getRecords = () => {
    axios.get('http://localhost:3000/api/getRecords', {
      params: { userId, brokerId }
    }).then(res => {
      console.log('res:', res)
      setList(res.data)
    })
  }

  const scrollToView = () => {
    document.querySelector('.view-to')?.scrollIntoView({behavior:'smooth',
    block: 'end'})
  }

  return <Container>
     <header className="header">

     </header>
     <main className="main" >
       {
         list.map((item:any) => {
           return (
            <ul key={item.id} className="chat-list-wrapper">
              <li className={
                item.submitId === item.userId? 'chat-list chat-dir': 'chat-list' }>
                <span className="chat-name">
                  <ImageView
                  width="30px"
                  height="30px"
                  round={true} src={item.avatar} />
                </span>
              </li>
              <li className={
                item.submitId === item.userId? 'chat-dir-li2': ''
                }>
                {item.content}
              </li>
            </ul>
           )
         })
       }

       <div className="view-to" style={{marginTop: '20px',width: '100vw', height: 10, background: 'red'}}></div>

     </main>
     <footer  ref={mainDom} className="footer">
       <input ref={inpt} /> <button onClick={() => {
           // 发送消息
           socket.emit('sendMsg', {
             userId,
             brokerId,
             content: inpt.current.value.trim(),
             submitId
           })
          //  socket.on('sendMsg', (data:any) => {
          //   console.log('data:', data)
          //   // 调用获取用户信息接口
          //   getRecords()
          // })
           inpt.current.value = ''
       }}>按钮</button>
     </footer>
  </Container>
}

export default Chat;

const Container = styled.div`
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .header {
    height: 45px;
    background: lightblue;
  }
  .main {
    flex: 1;
    overflow: auto;
    .chat-list-wrapper {
      width: 90%;
      line-height: 45px;
      overflow: auto;
      margin: 5%;
      .chat-list{
        width: 20%;
        float: left;
        /* background: #ccc; */
        height: 45px;
        .chat-name {
          display:inline-block ;
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      li:nth-child(2) {
        width: 80%;
        float: right;
        line-height: 25px;
      }
      .chat-dir {
        float: right;
      }
      .chat-dir-li2 {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  .footer {
    height: 45px;
    background: lightblue;
  }

`;
